﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Microsoft.Mtool.FSM;
using System.Configuration;

namespace MToolStudio
{
    public partial class VariableEditor : UserControl
    {
        public VariableEditor()
        {
            InitializeComponent();
            //combinator = new PictFile(ConfigurationManager.AppSettings["PictBinFile"], ConfigurationManager.AppSettings["PictWorkFolder"]);
        }

        public void InitPict()
        {
            combinator = new PictFile(ConfigurationManager.AppSettings["PictBinFile"], ConfigurationManager.AppSettings["PictWorkFolder"]); 
        }

        private List<PictInputVariable> variables = new List<PictInputVariable>();

        private PictFile combinator;

        private const string varRegExPattern = @"\$\((.*?)\)";

        public List<PictInputVariable> Variables
        {
            get { return variables; }
        }

        public int GetIndexOfVariable(string name)
        {
            for (int i = 0; i < variables.Count; i++)
                if (variables[i].Name == name) return i;
            return -1;
        }

        public void AddVariable(string name)
        {
            name = name.Trim();
            if (string.IsNullOrEmpty(name))
                return;
            if (GetIndexOfVariable(name) != -1) return;

            PictInputVariable pv = new PictInputVariable(name, new List<string>(), 2);
            variables.Add(pv);
            ListViewItem lvi = new ListViewItem(new string[] { pv.Name, "", pv.Order.ToString() });
            lvi.Tag = pv;
            listView_variables.Items.Add(lvi);
        }

        public void ParseVariables(string src)
        {
            src = src.Replace('\r', ' ').Replace('\n', ' ');
            Regex varRegEx = new Regex(varRegExPattern);
            Match mtch = varRegEx.Match(src);
            while (mtch.Success)
            {
                if (mtch.Groups.Count == 2)//has base class
                {
                    Logger.Instance.Verbose("Match variable, key:" + mtch.Groups[1].Value);
                    AddVariable(mtch.Groups[1].Value);
                }
                mtch = mtch.NextMatch();
            }
        }

        public void UpdateVariables(List<string> names)
        {
            List<PictInputVariable> newList = new List<PictInputVariable>();
            foreach (string n in names)
            {
                int index = GetIndexOfVariable(n);
                if (index == -1)
                    newList.Add(new PictInputVariable(n, new List<string>(), 2));
                else
                    newList.Add(variables[index]);
            }
            variables = newList;
        }

        public void UpdateListView()
        {
            listView_variables.Items.Clear();
            foreach (PictInputVariable pv in variables)
            {
                ListViewItem lvi = new ListViewItem(new string[] { pv.Name, pv.ValuesString, pv.Order.ToString() });
                lvi.Tag = pv;
                listView_variables.Items.Add(lvi);
            }
        }

        private void listBox_variables_DoubleClick(object sender, EventArgs e)
        {
            //MouseEventArgs me = e as MouseEventArgs;
            //if(me == null)
            //    return;
            ////Console.WriteLine("Double click");
            //if(listBox_variables.SelectedItem != null)
            //{
            //    TextBox tb = new TextBox();

            //    tb.Location = new Point(10, 10); //listBox_variables.PointToClient(new Point(me.X, me.Y));
            //    tb.Size = new Size(200, 200);
            //    tb.Multiline = true;
            //    Control rootControl = this;
            //    while (rootControl.Parent != null)
            //        rootControl = rootControl.Parent;
            //    rootControl.Controls.Add(tb);
            //    //tb.Show();
            //    //Refresh();
            //}
        }

        private void listBox_variables_Click(object sender, EventArgs e)
        {
            //Console.WriteLine("Single Click");
        }

        private void listBox_variables_MouseDown(object sender, MouseEventArgs e)
        {
            //Console.WriteLine("Mouse Down");
        }

        private void button_addVar_Click(object sender, EventArgs e)
        {
            //string varName = textBox_varName.Text.Trim();
            //if (string.IsNullOrEmpty(varName))
            //{
            //    return;
            //}
            //Variable toadd = new Variable(varName);
            //if (listBox_variables.Items.Contains(toadd))
            //{
            //    MessageBox.Show("Duplicate variable name!");
            //    return;
            //}
            ////variables.Add(varName, new Variable(varName));
            //listBox_variables.Items.Add(toadd);
            //textBox_varName.Text = "";
        }
        
        private void listView_variables_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void listView_variables_DoubleClick(object sender, EventArgs e)
        {
            if (listView_variables.SelectedItems.Count == 0)
                return;
            PictInputVariable piv = listView_variables.SelectedItems[0].Tag as PictInputVariable;
            if (piv == null)
                return;
            using (ModifyVariable mvForm = new ModifyVariable())
            {
                mvForm.Variable = piv;
                mvForm.ShowDialog();                
                listView_variables.SelectedItems[0].SubItems[1].Text = piv.ValuesString;
                listView_variables.SelectedItems[0].SubItems[2].Text = piv.Order.ToString();
            }
        }

        private void button_testPict_Click(object sender, EventArgs e)
        {
            combinator.Inputs = variables;
            List<PictOutputVarList> outputs = combinator.RunPict();
            StringBuilder sb = new StringBuilder();
            int iComb = 0;
            foreach (PictOutputVarList vl in outputs)
            {
                sb.AppendFormat("Combination #{0}: ", ++iComb);
                foreach (PictOutputVariable ov in vl.Variables)
                {
                    sb.AppendFormat("{0}={1} ", ov.Name, ov.Value);
                }
                sb.AppendLine();
            }
            textBox_combResults.Text = sb.ToString();
        }

        public List<PictOutputVarList> GetPictOutput()
        {
            combinator.Inputs = variables;
            return combinator.RunPict();
        }

        internal void Clear()
        {
            listView_variables.Items.Clear();
            textBox_combResults.Text = "";
            variables.Clear();
        }

        private void VariableEditor_Load(object sender, EventArgs e)
        {
           // combinator = new PictFile(ConfigurationManager.AppSettings["PictBinFile"], ConfigurationManager.AppSettings["PictWorkFolder"]);
        }
    }
}
